# Maintain an index of feeds by feed_id.

import threading

feed_index = {}
feed_index_lock = threading.Lock()

def FeedIDs():
  global feed_index
  global feed_index_lock

  feed_index_lock.acquire()
  keys = list(feed_index.keys())
  feed_index_lock.release()

  return keys

def GetFeed(feed_id):
  global feed_index_lock
  global feed_index

  feed_index_lock.acquire()
  try:
    feed = feed_index[feed_id]
  finally:
    feed_index_lock.release()

  return feed

def MapOverFeeds(func):
  global feed_index_lock
  global feed_index

  feed_index_lock.acquire()
  result = map(func, feed_index.values())
  feed_index_lock.release()

  return result

def AddIfUnique(add_func, url):
  global feed_index_lock
  global feed_index

  feed_index_lock.acquire()
  for feed in feed_index.values():
    if feed.url() == url:
      feed_index_lock.release()
      return None

  feed = add_func()
  feed_index[feed.feed_id()] = feed

  feed_index_lock.release()

  return feed

def Add(feed):
  global feed_index_lock
  global feed_index

  feed_index_lock.acquire()
  feed_index[feed.feed_id()] = feed
  feed_index_lock.release()

def Remove(feed_id):
  global feed_index_lock
  global feed_index

  feed_index_lock.acquire()
  try:
    del feed_index[feed_id]
  finally:
    feed_index_lock.release()
